package com.hzcx.app.simplechat.ui.home.adapter;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.util.ChatNoticeUtil;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.model.PublicModel;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.litepal.LitePal;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HomeSearchMsgAdapter extends BaseQuickAdapter<EMMessage, BaseViewHolder> {

    public String key;

    public HomeSearchMsgAdapter(@Nullable List<EMMessage> data) {
        super(R.layout.rv_item_home_search_msg, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, EMMessage item) {

        try {
            // 设置昵称，头像
            EMMessage message = item;
            final HxUserInfoBean[] userInfoBean = new HxUserInfoBean[1];
//        final GroupInfoBean[] groupInfoBean = new GroupInfoBean[1];
            if (message.getChatType() == EMMessage.ChatType.Chat || message.getChatType() == EMMessage.ChatType.GroupChat) { // 单聊
                String hxusername;
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    hxusername = message.getTo();
                } else {
                    if (message.direct() == EMMessage.Direct.SEND) {
                        hxusername = message.getTo();
                    } else {
                        hxusername = message.getFrom();
                    }
                }

                LitePal.where("hxusername=? and myUserId=?", hxusername, UserInfoUtil.getUserId() + "").findFirstAsync(HxUserInfoBean.class).listen(hxUserInfoBean -> {
                    if (hxUserInfoBean == null) {
                        if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                            GroupModel.getHxGroupInfo(mContext, hxusername, new BaseObserver<GroupInfoBean>() {
                                @Override
                                protected void onSuccess(GroupInfoBean data) {
                                    HxUserInfoBean userInfoBean1 = HxUserInfoBean.HxUserInfoBean(data);
                                    // 不用存此数据 不然导致群聊界面用户的头像错误使用群头像
                                    userInfoBean1.save();
                                    userInfoBean[0] = userInfoBean1;
                                    GlideUtils.loadImg(mContext, data.getGroup_image(), helper.getView(R.id.iv_head));
                                    if (EmptyUtils.isNotEmpty(data.getGroup_name())) {
                                        helper.setText(R.id.tv_nick_name, data.getGroup_id());
                                    } else {
                                        helper.setText(R.id.tv_nick_name, data.getGroup_name());
                                    }
                                }

                                @Override
                                public void onFailure(Throwable e, String errorMsg) {
                                }
                            });
                        } else {
                            PublicModel.getUserInfoByHx(mContext, hxusername, new BaseObserver<HxUserInfoBean>() {
                                @Override
                                protected void onSuccess(HxUserInfoBean data) {
                                    data.setHxusername(hxusername);
                                    data.setMyUserId(UserInfoUtil.getUserId());
                                    data.save();
                                    userInfoBean[0] = data;
                                    GlideUtils.loadImg(mContext, data.getAvatar(), helper.getView(R.id.iv_head));
                                    if (EmptyUtils.isNotEmpty(data.getRemarks_name())) {
                                        helper.setText(R.id.tv_nick_name, data.getRemarks_name());
                                    } else {
                                        helper.setText(R.id.tv_nick_name, data.getNickname());
                                    }
                                }
                            });
                        }
                    } else {
                        userInfoBean[0] = hxUserInfoBean;
                        GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                        if (EmptyUtils.isNotEmpty(hxUserInfoBean.getRemarks_name())) {
                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getRemarks_name());
                        } else {
                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                        }
                    }
                });
            } else { // room
            }

            EMTextMessageBody txtBody = (EMTextMessageBody) item.getBody();
            String str = txtBody.getMessage();
            Pattern p = Pattern.compile(key);
            Matcher m = p.matcher(str);
            String s = "";
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                if (start > 7) {
                    s = "..." + str.substring(start - 7, start) + key;
                } else {
                    s = str.substring(0, start) + key;
                }
                if (str.length() - end > 7) {
                    s = s + str.substring(end, end + 7) + "...";
                } else {
                    s = s + str.substring(end);
                }
            }

            helper.setText(R.id.tv_content, findSearch(mContext.getResources().getColor(R.color.color_2D7CFD), s, key));

            // 列表点击
            helper.getView(R.id.cons_content).setOnClickListener(view -> {
                if (userInfoBean[0] == null) {
                    ToastUtils.show("用户数据异常，请稍后重试");
                    return;
                }
                if (item.getChatType() == EMMessage.ChatType.GroupChat) {
                    ChatUtil.getInstance().toGroupChatUi(mContext, userInfoBean[0]);
                } else {
                    ChatUtil.getInstance().toChatUi(mContext, userInfoBean[0]);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setKey(String key) {
        this.key = key;
    }

    /**
     * 关键字高亮变色
     *
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return
     */
    public static SpannableString findSearch(int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        Pattern p = Pattern.compile(keyword);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return s;
    }
}
